package com.fone.player.util;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.http.impl.cookie.DateUtils;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningTaskInfo;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.ComponentName;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.database.sqlite.SQLiteDatabase;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Environment;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.Toast;

import com.fone.player.ApplicationManage;
import com.fone.player.R;
import com.fone.player.activity.FoneDefaultSettings;
import com.fone.player.activity.main.MainTabActivity;
import com.fone.player.activity.personal.LoginActivity;
import com.fone.player.activity.personal.PlayRecordFragment;
import com.fone.player.client.Callback;
import com.fone.player.client.DeclarationRst;
import com.fone.player.client.DeclarationRst.Tip;
import com.fone.player.client.Error;
import com.fone.player.client.QntRst;
import com.fone.player.client.Request;
import com.fone.player.client.Rst;
import com.fone.player.constant.FoneConstant;
import com.fone.player.entity.CacheVideo;
import com.fone.player.entity.NotificationBean;
import com.fone.player.entity.PlayRecord;
import com.fone.player.play.FonePlayerActivity;
import com.fone.player.play.PlayerAction;
import com.fone.player.play.PlayerFrom;
import com.fone.player.play.WebPlayerFrom;
import com.fone.player.play.WebViewPlayerActivity;
import com.fone.player.play.sohu.AppConst;
import com.fone.player.play.sohu.SohuPlayerActivity;
import com.fone.player.service.NotificationHandler;
import com.fone.player.storage.IFoneDatabase;
import com.fone.player.storage.StorageModule;
import com.letv.sdk.onehundredtv.video.BDVideoPartner;
import com.letv.sdk.onehundredtv.video.IVideo;
import com.letv.sdk.onehundredtv.video.LetvSdk;
import com.nostra13.universalimageloader.core.DisplayImageOptions;

/**
 * 一般工具类
 * 
 * @author kongxiaojun
 * @since 2014-5-4
 */
public class FoneUtil {

	private static String TAG = "FoneUtil";

	/**
	 * 把秒钟转换成分钟"mm:ss"显示
	 * 
	 * @return void
	 * @throws
	 */
	public static String second2MinuteStr(int second) {
		int min = second / 60;
		int sec = second % 60;
		String mins;
		String secs;
		if (min < 10) {
			mins = "0" + min;
		} else {
			mins = "" + min;
		}
		if (sec < 10) {
			secs = "0" + sec;
		} else {
			secs = "" + sec;
		}
		return mins + ":" + secs;
	}

	/**
	 * 判断网络是否连接
	 * 
	 * @param context
	 * @return
	 */
	public static boolean isNetOkWithToast(Context context) {

		if (context == null) {
			return false;
		}

		if (getCurrentNetType(context) == 0) {
			L.v(TAG, "isNetOkWithToast", "no_network_toast");
			Toast.makeText(context, R.string.no_network_toast, Toast.LENGTH_LONG).show();
		}
		return getCurrentNetType(context) != 0;
	}

	/**
	 * 判断网络是否连接
	 * 
	 * @param context
	 * @return
	 */
	public static boolean isNetOk(Context context) {
		return getCurrentNetType(context) != 0;
	}

	/**
	 * 
	 * @param context
	 * @return 1 : wifi 2:3g 3:gprs 0: no net
	 */
	public static int getCurrentNetType(Context context) {
		if (null == context) {
			return 0;
		}
		ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);// 获取系统的连接服务
		NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();// 获取网络的连接情况
		if (null != activeNetInfo) {
			L.v(TAG, "getNetType : ", activeNetInfo.toString());
			if (activeNetInfo.getType() == ConnectivityManager.TYPE_WIFI) {
				// 判断WIFI网
				return 1;
			} else if (activeNetInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
				TelephonyManager mTelephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
				int type = mTelephonyManager.getNetworkType();
				if (type == TelephonyManager.NETWORK_TYPE_UNKNOWN || type == TelephonyManager.NETWORK_TYPE_GPRS || type == TelephonyManager.NETWORK_TYPE_EDGE) {
					// 判断gprs网
					return 3;
				} else {
					// 判断3g网
					return 2;
				}
			}
		}
		return 0;
	}

	/**
	 * 数据加密
	 * 
	 * @param info
	 * @return
	 */
	public static String Md5(String plainText) {
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			md.update(plainText.getBytes());
			byte b[] = md.digest();

			int i;

			StringBuffer buf = new StringBuffer("");
			for (int offset = 0; offset < b.length; offset++) {
				i = b[offset];
				if (i < 0)
					i += 256;
				if (i < 16)
					buf.append("0");
				buf.append(Integer.toHexString(i));
			}

			return buf.toString();// 32位的加密

		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * Base64String
	 * 
	 * @param data
	 * @return
	 */
	public static String Base64Encode(String data) {
		String encodeData = "";
		try {
			encodeData = new String(Base64.encode(data.getBytes("UTF-8"), Base64.URL_SAFE | Base64.NO_WRAP), "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return encodeData;
	}

	/**
	 * Base64String
	 * 
	 * @param data
	 * @return
	 */
	public static String Base64Encode(byte[] data) {
		String encodeData = "";
		try {
			encodeData = new String(Base64.encode(data, Base64.URL_SAFE | Base64.NO_WRAP), "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return encodeData;
	}

	/**
	 * Toast 提示
	 * 
	 * @param context
	 * @param text
	 */
	public static void showToast(Context context, String text) {
		if (context != null && !TextUtils.isEmpty(text)) {
			Toast.makeText(context, text, Toast.LENGTH_SHORT).show();
		}
	}

	/**
	 * Toast 提示
	 * 
	 * @param context
	 * @param text
	 */
	public static void showToast(Context context, int resId) {
		Toast.makeText(context, resId, Toast.LENGTH_SHORT).show();
	}

	/**
	 * 处理url，去掉前面的"[host]"和"/player/"，该方法是临时的，以后随着url的变化可能就不需要该方法了
	 * 
	 * @param url
	 * @return
	 * @return String
	 * @throws
	 */
	public static String handleUrl(String url) {
		url = url.trim();
		if (url.startsWith("[host]")) {
			url = url.replace("[host]", "");
		}
		if (url.startsWith("/player")) {
			url = url.replace("/player", "");
		}
		return url;
	}

	public static String onlineUrl(String url) {
		url = url.trim();
		if (url.startsWith("[host]/player/")) {
			url = url.replace("[host]/player/", "");
		}
		return url;
	}

	/**
	 * 拼接 url 绝对路径
	 * 
	 * @param host
	 * @param shost
	 * @param url
	 * @return
	 */
	public static String getAbsoluteUrl(String host, String shost, String url) {
		if (TextUtils.isEmpty(url)) {
			return "";
		} else if (url.startsWith("http://")) {
			return url;
		} else if (url.startsWith("[host]") && !TextUtils.isEmpty(host)) {
			return host + url.substring(url.indexOf("]") + 1, url.length());
		} else if (url.startsWith("[shost]") && !TextUtils.isEmpty(shost)) {
			return shost + url.substring(url.indexOf("]") + 1, url.length());
		} else {
			return null;
		}
	}

	public static String getAbsoluteUrl(String host, String shost, String url, String cipher) {
		if (TextUtils.isEmpty(url)) {
			return "";
		} else if (url.startsWith("http://")) {
			return url;
		} else if (url.startsWith("[host]") && !TextUtils.isEmpty(host)) {
			return host + url.substring(url.indexOf("]") + 1, url.length()) + "&cipher=" + cipher;
		} else if (url.startsWith("[shost]") && !TextUtils.isEmpty(shost)) {
			return shost + url.substring(url.indexOf("]") + 1, url.length());
		} else {
			return null;
		}
	}

	/**
	 * 
	 * String 类型 转换为 Integer 类型
	 * 
	 * @param str
	 *            要转换的string
	 * @return Integer
	 * @return int
	 * @throws
	 */
	public static int String2Integer(String str) {
		int num = 0;
		try {
			num = Integer.valueOf(str);
		} catch (NumberFormatException e) {
			e.printStackTrace();
		}
		return num;
	}

	/**
	 * 
	 * String 类型 转换为 Long 类型
	 * 
	 * @param str
	 *            要转换的string
	 * @return Long
	 * @throws
	 */
	public static Long String2Long(String str) {
		Long num = (long) 0;
		try {
			num = Long.valueOf(str);
		} catch (NumberFormatException e) {
			e.printStackTrace();
		}
		return num;
	}

	/**
	 * 登陆成功后广播
	 * 
	 * @param context
	 * @param from
	 * @param type
	 */
	public static void sendLoginSuccess(Context context, String from, int type, boolean issend, String clid) {
		Intent intent = new Intent();
		intent.setAction(FoneConstant.BROADCAST_LOGIN_SUCCESS);
		intent.putExtra("payfrom", from);
		intent.putExtra("type", type);
		intent.putExtra("clid", clid);
		intent.putExtra("issend", issend);
		context.sendOrderedBroadcast(intent, null);
	}

	/**
	 * 计费跳转至登陆页
	 * 
	 * @param activity
	 * @param comefrom
	 *            1 点击头像注册 2 点击立即充值 3 点击成为VIP 4 付费影片计费跳转/点击权利页按钮跳转到登陆 5点击vip频道
	 *            加入vip按钮,7 其他
	 * @param feeFrom
	 *            计费使用
	 * @param feeType
	 *            计费使用
	 * @param userlist
	 *            计费使用
	 * @param clid
	 *            栏目id
	 */
	public static void feeToLoginPage(Context context, String comefrom, String feeFrom, int feeType, ArrayList<String> userlist, String clid) {
		Intent intent = new Intent(context, LoginActivity.class);
		if (comefrom != null) {
			intent.putExtra("loginfrom", comefrom);
		}
		intent.putExtra("payfrom", feeFrom);
		intent.putExtra("clid", clid);
		intent.putExtra("type", feeType);
		if (userlist != null && userlist.size() > 0) {
			intent.putExtra("userlist", userlist);
		}
		context.startActivity(intent);
	}

	/**
	 * 跳转至登陆页
	 * 
	 * @param activity
	 * @param comefrom
	 *            1 点击头像注册 2 点击立即充值 3 点击我的视频成为VIP 4 付费影片计费跳入 5点击vip频道 加入vip按钮 6
	 *            点击权利页按钮跳转到登陆,7 其他
	 */
	public static void toLoginPage(Context context, String comefrom) {
		feeToLoginPage(context, comefrom, "", -1, null, "");
	}

	/**
	 * 拼接地址(去掉 [host] [shost])
	 * 
	 * @param url
	 * @return
	 * @return String
	 * @throws
	 */
	public static String formatUrl(String url) {
		if (null == url) {
			L.e("FoneUtil", "nullPointer", "formatUrl------->url=null!");
			return null;
		}
		if (url.startsWith("[host]") || url.startsWith("[shost]")) {
			return url.substring(url.indexOf("]") + 1);
		} else {
			return url;
		}
	}

	/**
	 * 格式化日期
	 * 
	 * @param date
	 *            日期
	 * @param patten
	 *            模版例如："yyyy-MM-dd"
	 * @return String
	 * @throws
	 */
	@SuppressLint("SimpleDateFormat")
	public static String formatDate(Date date, String patten) {
		if (date == null || TextUtils.isEmpty(patten)) {
			return null;
		}
		SimpleDateFormat sdf = new SimpleDateFormat(patten);
		return sdf.format(date);
	}

	/**
	 * 解析日期
	 * 
	 * @param source
	 *            源字符串
	 * @param patten
	 *            模版例如："yyyy-mm-dd"
	 * @return
	 * @return Date
	 * @throws
	 */
	@SuppressLint("SimpleDateFormat")
	public static Date parserDate(String source, String patten) {
		if (TextUtils.isEmpty(source) || TextUtils.isEmpty(patten)) {
			return null;
		}
		SimpleDateFormat sdf = new SimpleDateFormat(patten);
		try {
			return sdf.parse(source);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 添加一个一次性闹钟
	 * 
	 * @param context
	 * @param type
	 *            闹钟类型 AlarmManager.ELAPSED_REALTIME、
	 *            AlarmManager.ELAPSED_REALTIME_WAKEUP、AlarmManager.RTC、
	 *            AlarmManager.RTC_WAKEUP、AlarmManager.POWER_OFF_WAKEUP
	 * @param startTime
	 *            响铃时间 毫秒的时间戳
	 * @param pi
	 *            PendingIntent
	 * @return void
	 * @throws
	 */
	public static void addOnceAlarm(Context context, int type, long startTime, PendingIntent pi) {
		AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
		am.set(type, startTime, pi);
	}

	/**
	 * 取消一个闹钟
	 * 
	 * @param context
	 * @param pi
	 * @return void
	 * @throws
	 */
	public static void cancelAlarm(Context context, PendingIntent pi) {
		AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
		am.cancel(pi);
	}

	/**
	 * * 播放缓存视频
	 * 
	 * @param activity
	 *            此处需要activity
	 * @param from
	 *            点击来源,参考PlayerFrom常量
	 * @param videos
	 *            缓存视频bean
	 * @param index
	 *            当前播放ArrayList的索引个，从0开始
	 * @return void
	 * @throws
	 */
	public static void openCacheVideo(Context activity, int from, ArrayList<CacheVideo> videos, int index) {
		if (videos.get(index).getDurations() != null && videos.get(index).getDurations().length > 1) {
			if (videos.get(index).getDurations()[0] == 0) {
				L.v(TAG, "FoneUtil : --多片视频时长是0--");
				Toast.makeText(activity, "播放失败：缓存视频时长为0", Toast.LENGTH_SHORT).show();
				return;
			}
		}
		if (videos.get(index).getUrls() == null || videos.get(index).getUrls().length == 0 || TextUtils.isEmpty(videos.get(index).getUrls()[0])) {
			L.v(TAG, "FoneUtil : --多片视频url是空");
			Toast.makeText(activity, "播放失败：缓存视频url为空", Toast.LENGTH_SHORT).show();
			return;
		}
		Intent intent = new Intent(activity, FonePlayerActivity.class);
		intent.putExtra("from", from);
		intent.putExtra("action", PlayerAction.FULLPLAY.name());
		intent.putParcelableArrayListExtra("cachevideos", videos);
		intent.putExtra("index", index);
		activity.startActivity(intent);
	}

	/**
	 * 打开一个在线视频
	 * 
	 * @param context
	 *            上下文
	 * @param from
	 *            点击来源,参考PlayerFrom常量
	 * @param action
	 *            点击动作,参考PlayerAction枚举类
	 * @param vgurl
	 *            视频详情url
	 * @param xyzplayurl
	 *            视频播放url
	 * @param dnfs
	 *            清晰度，如"1,2,3"代表支持标清、高清、超清
	 * @param name
	 *            视频名称
	 * @throws
	 */
	public static void openOnlineVideo(Context context, int from, PlayerAction action, String vgurl, String xyzplayurl, String dnfs, String name) {
		if (TextUtils.isEmpty(xyzplayurl) && TextUtils.isEmpty(vgurl)) {
			L.v(TAG, "详情地址和播放地址至少需要一个！");
			return;
		}
		if (from == 0) {
			L.v(TAG, "来源错误，参考PlayerFrom常量！");
			return;
		}
		if (action == null) {
			L.v(TAG, "动作不能为空，参考PlayerAction枚举！");
			return;
		}
		if (action == PlayerAction.DETAIL) {
			if (TextUtils.isEmpty(vgurl)) {
				L.v(TAG, "打开详情页播放时详情地址不能为空！");
				return;
			}
		}
		Intent intent = new Intent(context, FonePlayerActivity.class);
		intent.putExtra("from", from);
		intent.putExtra("action", action.name());
		intent.putExtra("vgdetail", vgurl);
		intent.putExtra("xyzplay", xyzplayurl);
		if (!TextUtils.isEmpty(name)) {
			intent.putExtra("name", name);
		}
		if (from == PlayerFrom.NOTIFICATION_EXTERNAL || from == PlayerFrom.NOTIFY_SUBSCRIBE || from == PlayerFrom.NOTIFY_COLLECTION) {// 外部通知
			if (ActivityQueue.getSize() > 0) {
				// 判断是否在前台
				if (!FoneUtil.isAppOnForeground(context)) {
					if (ActivityQueue.popIndex(0) instanceof FonePlayerActivity) { // 如果当前页为播放页面
						Intent mIntent = new Intent(Intent.ACTION_MAIN);
						mIntent.putExtra("from", from);
						mIntent.putExtra("action", action.name());
						mIntent.putExtra("vgdetail", vgurl);
						mIntent.putExtra("xyzplay", xyzplayurl);
						if (!TextUtils.isEmpty(name)) {
							mIntent.putExtra("name", name);
						}
						FoneUtil.wakeUpfromBackground(ActivityQueue.popIndex(0).getClass(), mIntent);
						return;
					} else {
						FoneUtil.wakeUpfromBackground(ActivityQueue.popIndex(0).getClass(), null);
					}
				}
				ActivityQueue.popIndex(0).startActivity(intent);
			} else {
				intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				context.startActivity(intent);
			}
			return;
		}
		context.startActivity(intent);
	}

	/**
	 * 打开第三方播放器
	 * 
	 * @param context
	 *            上下文
	 * @param from
	 *            来源 WebPlayerFrom
	 * @param ourl
	 *            原始地址
	 * @param xyzplayurl
	 *            播放地址
	 * @param name
	 *            名称
	 * @param btnply
	 *            是否显示播放按钮 0不显示，1显示
	 * @return void
	 * @throws
	 */
	public static void open3rdPlayer(Context context, WebPlayerFrom from, String ourl, String xyzplayurl, String name, int btnply, String weibourl,String pic) {

		if (ourl.contains("sohu.com")) {// 打开搜狐SDK播放器
			openSohuPlayer(context, "111", "100tv", ourl);
			save3rdRecord(xyzplayurl, ourl, btnply, weibourl, pic, name);
			return;
		} else if (ourl.contains("letv.com")) {
			if (openLetvSdkPlayer(context, ourl)) {
				save3rdRecord(xyzplayurl, ourl, btnply, weibourl, pic, name);
				return;
			}
		}

		Intent intent = new Intent(context, WebViewPlayerActivity.class);
		intent.putExtra("from", from.name());
		intent.putExtra("xyzplay", xyzplayurl);
		intent.putExtra("ourl", ourl);
		intent.putExtra("btnply", btnply);
		intent.putExtra("weibourl", weibourl);
		intent.putExtra("name", name);
		if (from == WebPlayerFrom.NOTIFICATION) {
			if (ActivityQueue.getSize() > 0) {
				// 判断是否在前台
				if (!FoneUtil.isAppOnForeground(context)) {
					if (ActivityQueue.popIndex(0) instanceof WebViewPlayerActivity) { // 如果当前页为播放页面
						Intent mIntent = new Intent(Intent.ACTION_MAIN);
						intent.putExtra("from", from.name());
						intent.putExtra("xyzplay", xyzplayurl);
						intent.putExtra("ourl", ourl);
						intent.putExtra("btnply", btnply);
						intent.putExtra("weibourl", weibourl);
						intent.putExtra("name", name);
						FoneUtil.wakeUpfromBackground(ActivityQueue.popIndex(0).getClass(), mIntent);
						return;
					} else {
						FoneUtil.wakeUpfromBackground(ActivityQueue.popIndex(0).getClass(), null);
					}
					FoneUtil.wakeUpfromBackground(ActivityQueue.popIndex(0).getClass(), null);
				}
				ActivityQueue.popIndex(0).startActivity(intent);
			} else {
				intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				context.startActivity(intent);
			}
			return;
		}
		context.startActivity(intent);
	}

	/**
	 * 打开搜狐视频SDK播放
	 * 
	 * @param context
	 * @param id
	 * @param keyword
	 * @param ourl
	 * @return void
	 * @throws
	 */
	public static void openSohuPlayer(Context context, String id, String keyword, String ourl) {
		try {
			ourl = URLEncoder.encode(FoneUtil.Base64Encode(ourl), "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		Intent intent = new Intent();
		intent.putExtra(AppConst.INTENT_KEY_ID, id);
		intent.putExtra(AppConst.INTENT_KEY_KEYWORD, keyword);
		intent.putExtra(AppConst.INTENT_KEY_OURL, ourl);
		intent.setClass(context, SohuPlayerActivity.class);
		context.startActivity(intent);
	}

	/**
	 * 打开乐视SDK播放器
	 * 
	 * @param context
	 * @param ourl
	 * @return
	 * @return boolean
	 * @throws
	 */
	public static boolean openLetvSdkPlayer(Context context, String ourl) {
		long vid = getLetvVidByUrl(ourl);
		if (vid <= 0) {
			return false;
		}
		LetvSdk.getInstance().setConetxt(context);// 设置context
		LetvSdk.getInstance().registerCallBack(new com.letv.sdk.onehundredtv.video.BDVideoPartner.Callback() {
			@Override
			public void onEvent(final int event, final String name, IVideo video) {
				// 播放器回调
				if (event == BDVideoPartner.EVENT_PLAY_START) {
				} else if (event == BDVideoPartner.EVENT_DLNA_PLAY) {
				} else if (event == BDVideoPartner.EVENT_PLAY_PAUSE) {
				} else if (event == BDVideoPartner.EVENT_PLAY_STOP) {// 播放器退出
				} else if (event == BDVideoPartner.EVENT_PLAY_RESUME) {
				} else if (event == BDVideoPartner.EVENT_PLAY_NEXT) {
				} else if (event == BDVideoPartner.EVENT_PLAY_PREV) {
				} else if (event == BDVideoPartner.EVENT_FAVORITE) {// 收藏
				} else if (event == BDVideoPartner.EVENT_FAVORITE_CANCEL) {// 取消收藏
				} else if (event == BDVideoPartner.EVENT_START_DOWNLOAD) {// 下载
					// 下载地址获取地方
					LetvSdk.getInstance().changeDownState(1);// 0是下载 1是已下载
				} else if (event == BDVideoPartner.EVENT_PLAY_PREV) {

				}
			}
		});// 注册回调

		IVideo video1 = new IVideo();
		video1.vID = vid;// 只有vid
		video1.mCurrentTime = 0;// 设置播放进度 单位s
		video1.mIsFavorite = true;
		video1.mDownloadStatus = IVideo.DOWNLOAD_NONE;
		LetvSdk.getInstance().play(context, video1);

		return true;
	}

	/**
	 * 取cid
	 * 
	 * @param url
	 * @return
	 * @return String
	 * @throws
	 */
	public static String getCIdByUrl(String url) {
		if (TextUtils.isEmpty(url)) {
			L.v(TAG, "url是空的");
			return null;
		}
		if (url.contains("&cid=")) {
			int index = url.indexOf("&cid=");
			int endIndex = url.indexOf("&", index + 5);
			if (endIndex == -1) {
				return url.substring(index + 5);
			} else {
				return url.substring(index + 5, endIndex);
			}
		} else if (url.contains("cid=")) {
			int index = url.indexOf("cid=");
			int endIndex = url.indexOf("&", index + 4);
			if (endIndex == -1) {
				return url.substring(index + 4);
			} else {
				return url.substring(index + 4, endIndex);
			}
		} else {
			L.v(TAG, "url里没有cid");
			L.v(TAG, "url = " + url);
			return "0";
		}
	}

	/**
	 * 取ccid
	 * 
	 * @param url
	 * @return
	 * @return String
	 * @throws
	 */
	public static String getCCIdByUrl(String url) {
		if (TextUtils.isEmpty(url)) {
			L.v(TAG, "url是空的");
			return null;
		}
		if (url.contains("ccid=")) {
			int index = url.indexOf("ccid=");
			int endIndex = url.indexOf("&", index + 5);
			if (endIndex == -1) {
				return url.substring(index + 5);
			} else {
				return url.substring(index + 5, endIndex);
			}
		} else {
			L.v(TAG, "url里没有ccid");
			return null;
		}
	}

	/**
	 * 取clid
	 * 
	 * @param url
	 * @return
	 * @return String
	 * @throws
	 */
	public static String getCLIdByUrl(String url) {
		if (TextUtils.isEmpty(url)) {
			L.v(TAG, "url是空的");
			return null;
		}
		if (url.contains("clid=")) {
			int index = url.indexOf("clid=");
			int endIndex = url.indexOf("&", index + 5);
			if (endIndex == -1) {
				return url.substring(index + 5);
			} else {
				return url.substring(index + 5, endIndex);
			}
		} else {
			L.v(TAG, "url里没有clid");
			return null;
		}
	}

	public static String getUerydataByUrl(String url) {
		if (TextUtils.isEmpty(url)) {
			L.v(TAG, "url是空的");
			return null;
		}
		if (url.contains("querydata=")) {
			int index = url.indexOf("querydata=");
			int endIndex = url.indexOf("&", index + 10);
			if (endIndex == -1) {
				return url.substring(index + 10);
			} else {
				return url.substring(index + 10, endIndex);
			}
		} else {
			L.v(TAG, "url里没有querydata");
			return null;
		}
	}

	/**
	 * 取videoid
	 * 
	 * @param url
	 * @return
	 * @return String
	 * @throws
	 */
	public static String getVideoIdByUrl(String url) {
		if (TextUtils.isEmpty(url)) {
			L.v(TAG, "url是空的");
			return null;
		}
		if (url.contains("videoid=")) {
			int index = url.indexOf("videoid=");
			int endIndex = url.indexOf("&", index + 8);
			if (endIndex == -1) {
				return url.substring(index + 8);
			} else {
				return url.substring(index + 8, endIndex);
			}
		} else {
			L.v(TAG, "url里没有videoid");
			return null;
		}
	}

	/**
	 * 隐藏输入法
	 * 
	 * @param editText
	 * @param context
	 */
	public static void hideInputMethod(EditText editText, Context context) {
		InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
		if (imm.isActive()) {
			imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);
		}
	}

	/**
	 * 隐藏输入法
	 * 
	 * @param context
	 */
	public static void hideInputMethod(Activity activity) {
		InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
		if (activity.getCurrentFocus() != null) {
			imm.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
		}
	}

	/**
	 * 清除播放器默认设置
	 * 
	 * @param context
	 * @param classname
	 */
	public static void resetDefaultSetting(Context context, String classname) {
		if (null == context) {
			return;
		}
		L.v(TAG, " resetDefaultSetting classname ", classname);
		String className = classname;
		// getClass().getPackage().getName();
		// className = "com.fone.player";
		List<IntentFilter> intentList = new ArrayList<IntentFilter>();
		List<ComponentName> cnList = new ArrayList<ComponentName>();
		PackageManager localPackageManager = context.getPackageManager();
		localPackageManager.getPreferredActivities(intentList, cnList, null);
		IntentFilter dhIF;
		L.v(TAG, " resetDefaultSetting intentList.size():", intentList.size());
		for (int i = 0; i < intentList.size(); i++) {
			dhIF = intentList.get(i);
			String apptype = null;
			String appaction = null;
			String appcategory = null;
			int ifschemeCount = dhIF.countDataSchemes();
			int iftypeCount = dhIF.countDataTypes();
			String appname = cnList.get(i).getPackageName();
			L.v(TAG, " resetDefaultSetting cnList.get(i).getPackageName(): ", cnList.get(i).getPackageName());
			if (ifschemeCount > 0 && !appname.equals(className)) {
				String dataScheme = dhIF.getDataScheme(0);
				appaction = dhIF.getAction(0);
				appcategory = dhIF.getCategory(0);

				Intent intent = new Intent(appaction);
				intent.addCategory(appcategory);
				Uri data = null;
				if ("rtsp".equals(dataScheme))
					data = Uri.parse("rtsp://");
				else if ("http".equals(dataScheme))
					data = Uri.parse("http://");
				if (data != null)
					intent.setData(data);
				replaceSet(context, className, intent);
			}
			if (iftypeCount > 0 && null != dhIF.getDataType(0)) {
				apptype = dhIF.getDataType(0);
				appaction = dhIF.getAction(0);
				appcategory = dhIF.getCategory(0);
				Intent intent = new Intent(appaction);
				intent.addCategory(appcategory);
				L.v(TAG, ">>>>apptype: ", apptype);
				String apptypeSub = null;
				if (apptype.length() >= 5) {
					apptypeSub = apptype.substring(0, 5);
				} else {
					return;
				}
				L.v(TAG, " resetDefaultSetting apptypeSub ", apptypeSub);
				L.v(TAG, " resetDefaultSetting appname ", appname);
				if ((apptypeSub.equals("audio") || apptypeSub.equals("video")) && !appname.equals(className)) {
					FoneConstant.isClearDefaultSetting = true;
					L.v(TAG, " resetDefaultSetting ", " end  ");
				}
				if ((apptypeSub.equals("audio") || apptypeSub.equals("video")) && !appname.equals(className)) {
					if (ifschemeCount >= 0) {
						if (apptype.equals("audio") || apptype.equals("video/*") || apptype.equals("")) {
							intent.setType(apptype.substring(0, 5) + "/*");
						} else {
							intent.setType(apptype);
						}
						replaceSet(context, className, intent);

					}

				}
				if ((apptypeSub.equals("audio") || apptypeSub.equals("video")) && !appname.equals(className)) {
					if (ifschemeCount >= 0) {

						Uri data = Uri.fromFile(new File(Environment.getExternalStorageDirectory().getPath()));
						intent.setDataAndType(data, apptype);
					}
					replaceSet(context, className, intent);

				}
				if ((apptypeSub.equals("audio") || apptypeSub.equals("video")) && !appname.equals(className)) {
					if (ifschemeCount >= 0) {
						intent.setDataAndType(null, "video/*");
					}
					// replaceSet(context, className, intent);

				}
			}
		}
	}

	/**
	 * 格式化时间 转为 TimeMillis
	 * 
	 * @param currentTime
	 * @param inFormat
	 * @return
	 */
	public static String FormatedTime2String(String currentTime, String inFormat) {

		if (TextUtils.isEmpty(currentTime) || TextUtils.isEmpty(inFormat)) {
			L.v(TAG, "FormatedTime2String", "currentTime : " + currentTime + " inFormat : " + inFormat);
			return currentTime;
		}
		Date data = null;
		try {
			data = DateUtils.parseDate(currentTime, new String[] { inFormat });
		} catch (Exception e) {
			L.e(TAG, "FormatedTime2String", e.getMessage());
			return currentTime;
		}
		return String.valueOf(data.getTime());
	}

	/**
	 * 格式化数字
	 * 
	 * @param d
	 *            数字
	 * @param pattern
	 *            模型 "0.00"
	 * @return String
	 * @throws
	 */
	public static String formatNumber(double d, String pattern) {
		String s = "";
		try {
			if (pattern == null)
				pattern = "0.00";
			DecimalFormat df = new DecimalFormat(pattern);
			s = df.format(d);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return s;
	}

	@SuppressLint("SimpleDateFormat")
	public static synchronized void replaceSet(Context context, String names, Intent intent) {
		if (null == context) {
			return;
		}
		L.v(TAG, "replaceSet", "replaceSet");
		PackageManager localPackageManager = context.getPackageManager();
		String strDefault = "";
		strDefault = FoneDefaultSettings.class.getName();
		L.v(TAG, "strDefault : ", strDefault);
		ComponentName localComponentName = new ComponentName("com.fone.player", strDefault);
		localPackageManager.setComponentEnabledSetting(localComponentName, 1, 1);
		localPackageManager.resolveActivity(intent, 0);
		localPackageManager.setComponentEnabledSetting(localComponentName, 2, 1);
	}

	@SuppressLint("SimpleDateFormat")
	public static String getCurrentTime(long currentTime) {
		SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
		Date curDate = new Date(currentTime);
		String currentDate = formatter.format(curDate);
		return currentDate;
	}

	@SuppressLint("SimpleDateFormat")
	public static String getTime() {
		Date currentTime = new Date();
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		return formatter.format(currentTime);
	}

	/**
	 * 判断是否在前台
	 * 
	 * @param context
	 * @return
	 */
	public static boolean isAppOnForeground(Context context) {
		// Returns a list of application processes that are running on the
		// device
		ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
		List<RunningTaskInfo> tasks = activityManager.getRunningTasks(1);
		if (!tasks.isEmpty()) {
			ComponentName topActivity = tasks.get(0).topActivity;
			if (topActivity.getPackageName().equals(context.getPackageName())) {
				return true;
			}
		}
		return false;
	}

	/**
	 * 从后台唤醒应用
	 * 
	 * @param c_name
	 */
	public static void wakeUpfromBackground(Class<? extends Activity> clazz, Intent mIntent) {

		if (mIntent == null) {
			Intent intent = new Intent(Intent.ACTION_MAIN);
			intent.setClass(ApplicationManage.getGlobalContext(), clazz);
			intent.addCategory(Intent.CATEGORY_LAUNCHER);
			intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
			ApplicationManage.getGlobalContext().startActivity(intent);
		} else {
			mIntent.setClass(ApplicationManage.getGlobalContext(), clazz);
			mIntent.addCategory(Intent.CATEGORY_LAUNCHER);
			mIntent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
			ApplicationManage.getGlobalContext().startActivity(mIntent);
		}

	}

	/**
	 * 请求计费通知
	 * 
	 * @param mContext
	 */
	public static void requestFeeNotification(final Context mContext) {

		writeNotificationLog("计费通知请求");

		Request.getNotifcationInstance(mContext).qnt(1, new Callback<QntRst>() {

			@Override
			public void onSuccess(QntRst t) {
				// TODO Auto-generated method stub
				L.v(TAG, "requestFeeNotification onSuccess", "QntRst : " + t.toString());
				if (t.result != 0) {
					if (t.error != null) {
						L.v(TAG, "requestFeeNotification onSuccess", "t.error.errorcode : " + t.error.errorcode + "  t.error.errormsg : " + t.error.errormsg);
						writeNotificationLog("计费通知请求 结果 :" + t.toString());
					}
					return;
				}
				// 发送通知
				NotificationHandler.sendNotifications(mContext, t);
			}

			@Override
			public void onFailure(Error error) {

				String errorStr = "计费通知请求结果  isNetworkError : 请求超时 " + error.isNetworkError() + " status : " + error.getStatus() + " reason : " + error.getReason();
				L.v(TAG, "requestFeeNotification onFailure", errorStr);
				writeNotificationLog(errorStr);
			}
		});
	}

	/**
	 * 获取法律声明
	 * 
	 * @param mContext
	 */
	public static void requestDeclarations(final Context mContext) {
		if (FoneUtil.isNetOk(mContext)) {
			Request.getInstance().declaration("5,6,7,8,9,10,12,13,17,19", new Callback<DeclarationRst>() {

				@Override
				public void onSuccess(final DeclarationRst t) {
					L.v(TAG, "requestDeclarations", "t.result = " + t.result);
					if (t.result != 0) {
						return;
					}
					// TODO 存入本地
					if (t.tips != null && t.tips.tipList != null && t.tips.tipList.size() > 0) {
						new Thread() {
							public void run() {
								saveDeclarations(mContext, t);
							};
						}.start();
					}
				}

				@Override
				public void onFailure(Error error) {
					L.v(TAG, "requestDeclarations onFailure", "isNetworkError : " + error.isNetworkError() + " status : " + error.getStatus() + " reason : " + error.getReason());
				}
			});
		}
	}

	/**
	 * 存储 Declarations
	 */
	private static void saveDeclarations(Context mContext, DeclarationRst t) {

		SharedPreferences declarationSp = mContext.getSharedPreferences(FoneConstant.FONE_SP_DECLARATION_SP, Context.MODE_PRIVATE);
		Editor edit = declarationSp.edit();
		for (Tip tip : t.tips.tipList) {
			try {
				switch (Integer.valueOf(tip.type)) {
				case 5:// 缓存法律声明
					edit.putString(FoneConstant.CACHE_LEGAL_NOTICE, tip.cnt);
					break;
				case 6:// 搜索法律声明
					edit.putString(FoneConstant.SEARCH_LEGAL_NOTICE, tip.cnt);
					break;
				case 7:// 详情页法律声明
					edit.putString(FoneConstant.DETAIL_LEGAL_NOTICE, tip.cnt);
					break;
				case 8:// 热点接口法律声明
					edit.putString(FoneConstant.HOT_LEGAL_NOTICE, tip.cnt);

					break;
				case 9:// 剧集法律声明
					edit.putString(FoneConstant.EPISODE_LEGAL_NOTICE, tip.cnt);

					break;
				case 10:// 栏目法律声明
					edit.putString(FoneConstant.PROGRAM_LEGAL_NOTICE, tip.cnt);

					break;
				case 12:// 直播法律声明
					edit.putString(FoneConstant.LIVE_LEGAL_NOTICE, tip.cnt);

					break;
				case 13:// 设置法律声明
					edit.putString(FoneConstant.SETTING_LEGAL_NOTICE, tip.cnt);

					break;
				case 17:// 分享语
					edit.putString(FoneConstant.SHARE_WORD, tip.cnt);

					break;
				case 19:// 注册条款及隐私声明
					edit.putString(FoneConstant.REGISTER_LEGAL_NOTICE, tip.cnt);

					break;
				default:
					break;
				}
				L.v(TAG, "saveDeclarations", "tip.cnt = " + tip.cnt);
			} catch (Exception e) {
				L.e(TAG, "saveDeclarations", e.getMessage());
			}
		}
		edit.commit();
	}

	/**
	 * @param mContext
	 * @param type
	 *            FoneConstant.SETTING_LEGAL_NOTICE 设置法律声明
	 *            FoneConstant.SEARCH_LEGAL_NOTICE 搜索法律声明
	 *            FoneConstant.CACHE_LEGAL_NOTICE 缓存法律声明
	 *            FoneConstant.DETAIL_LEGAL_NOTICE 详情页法律声明
	 *            FoneConstant.HOT_LEGAL_NOTICE 热点接口法律声明
	 *            FoneConstant.EPISODE_LEGAL_NOTICE 剧集法律声明
	 *            FoneConstant.PROGRAM_LEGAL_NOTICE 栏目法律声明
	 *            FoneConstant.LIVE_LEGAL_NOTICE 直播法律声明 FoneConstant.SHARE_WORD
	 *            分享语 FoneConstant.REGISTER_LEGAL_NOTICE 注册条款及隐私声明
	 */
	public static String getDeclaration(Context mContext, String type) {
		SharedPreferences declarationSp = mContext.getSharedPreferences(FoneConstant.FONE_SP_DECLARATION_SP, Context.MODE_PRIVATE);
		return declarationSp.getString(type, "");
	}

	/**
	 * 通知上报
	 * 
	 * @param type
	 *            8 内部通知 9 外部通知
	 * @param num
	 *            通知数量
	 */
	public static void reportNotification(final int type, int num, ArrayList<NotificationBean> notificationList) {

		L.v(TAG, "reportNotification", " type : " + type + " num : " + num);
		String data = "";
		if (num > 0) {
			data = "{(" + type + "," + num + ")}";
			L.v(TAG, "reportNotification", " data : " + data);

		}
		StringBuilder notifyid = new StringBuilder();
		notifyid.append("[");
		boolean isFirst = true;
		for (int i = 0; i < notificationList.size(); i++) {
			NotificationBean notificationBean = notificationList.get(i);

			L.v(TAG, "reportNotification", "NotificationContentType : " + notificationBean.getNotificationContentType());
			if (!(notificationBean.getNotificationContentType() == NotificationBean.NOTIFICATION_CONTENT_TYPE_GIFT || notificationBean.getNotificationContentType() == NotificationBean.NOTIFICATION_CONTENT_TYPE_BILLING || notificationBean.getNotificationContentType() == NotificationBean.NOTIFICATION_CONTENT_TYPE_RECHARGE)) {
				continue;
			}

			if (isFirst) {
				notifyid.append("{type:");
				isFirst = false;
			} else {
				notifyid.append(",{type:");
			}
			notifyid.append(notificationBean.getNotificationContentType());
			notifyid.append(",id:'");
			notifyid.append(notificationBean.getNotificationServerId().substring(0, notificationBean.getNotificationServerId().indexOf("_")));
			notifyid.append("'}");
		}
		notifyid.append("]");

		String notifyidString = notifyid.toString();
		L.v(TAG, "reportNotification", " notifyid : " + notifyidString);
		if (notifyidString.equals("[]")) {
			notifyidString = "";
		}

		String reportNotificationLog = "data : " + data + " notifyidString : " + notifyidString;

		L.v(TAG, "reportNotification", reportNotificationLog);
		if (TextUtils.isEmpty(data) && TextUtils.isEmpty(notifyidString)) {
			return;
		}

		writeNotificationLog("接收通知上报  :   " + reportNotificationLog + " cipher : " + Request.getInstance().getCipher());

		Request.getInstance().rpqnt(data, notifyidString, new Callback<Rst>() {

			@Override
			public void onSuccess(Rst t) {
				L.v(TAG, "reportNotification", "t.result = " + t.result);
				writeNotificationLog("type : " + type + "  reportNotification  t.result = " + t.result);
			}

			@Override
			public void onFailure(Error error) {
				String errorLog = "  reportNotification onFailure   isNetworkError : " + error.isNetworkError() + " status : " + error.getStatus() + " reason : " + error.getReason();

				L.v(TAG, "reportNotification onFailure", "isNetworkError : " + error.isNetworkError() + " status : " + error.getStatus() + " reason : " + error.getReason());

				writeNotificationLog("type : " + type + errorLog);

			}
		});

	}

	/**
	 * 通过原始地址 获取重定向后直接播放地址
	 * 
	 * @param initialUrl
	 *            重定向地址
	 * @param cookie
	 *            重定向需要的cookie
	 * @return
	 */
	public static String getAbsolutePlayUrl(String initialUrl, String cookie) {

		L.v(TAG, "getAbsolutePlayUrl", "initialUrl : " + initialUrl + " cookie : " + cookie);
		try {
			URL url = new URL(initialUrl);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setConnectTimeout(5 * 1000);
			conn.setReadTimeout(10 * 1000);
			conn.setRequestMethod("GET");
			conn.setInstanceFollowRedirects(false);
			conn.setRequestProperty("Cookie", cookie);
			conn.setRequestProperty("Charset", "UTF-8");
			conn.connect();
			int responseCode = conn.getResponseCode();
			L.v(TAG, "getAbsolutePlayUrl", "" + responseCode);
			if (responseCode == 302) {
				String locationUrl = conn.getHeaderField("Location");
				return locationUrl;
			}

		} catch (Exception e) {
			L.e(TAG, "getAbsolutePlayUrl", e.getMessage());
		}
		return null;
	}

	/**
	 * 创建一个图片显示DisplayImageOptions
	 * 
	 * @param id
	 * @return
	 * @return DisplayImageOptions
	 * @throws
	 */
	public static DisplayImageOptions createDisplayImageOptionsByDrawableId(int id) {
		return new DisplayImageOptions.Builder().showImageOnLoading(id).showImageForEmptyUri(id).showImageOnFail(id).cacheInMemory(true).cacheOnDisk(true).considerExifParams(true).build();
	}

	// private static String stream2String(InputStream inputStream){
	//
	// StringBuilder sResult = new StringBuilder();
	// BufferedReader in = new BufferedReader(new
	// InputStreamReader(inputStream));
	// String sCurrentLine = null;
	//
	// try{
	// while ((sCurrentLine = in.readLine()) != null) {
	// System.out.println("");
	// sResult.append(sCurrentLine.trim());
	// }
	// }catch(Exception e){
	// try {
	// in.close();
	// } catch (IOException e1) {
	// // TODO Auto-generated catch block
	// e1.printStackTrace();
	// }
	// }
	// return sResult.toString();
	// }

	public static void setRoundButtonImage() {
		PlayRecord fristPlayRecord = StorageModule.getInstance().getPlayRecordByPlayRecordSynchronzieType();
		if (fristPlayRecord != null) {
			int progress = (int) ((float) (fristPlayRecord.getPlayRecordAlreadyPlayTime()) / (float) (fristPlayRecord.getPlayRecordTotalTime()) * 100);

			if (fristPlayRecord.getPlayRecordType() == PlayRecord.RECORD_PLAYER_LOCAL || fristPlayRecord.getPlayRecordType() == PlayRecord.RECORD_WEB_NETWORK || fristPlayRecord.getPlayRecordType() == PlayRecord.RECORD_PLAYER_CACHE) {
				MainTabActivity.setRoundButtonImage(fristPlayRecord.getPlayRecordImageUrl(), true, progress);// 设置中间按钮图片
			} else {
				MainTabActivity.setRoundButtonImage(fristPlayRecord.getPlayRecordImageUrl(), false, progress);// 设置中间按钮图片
			}
		} else {
			MainTabActivity.setRoundButtonImage(null, true, 0);// 设置中间按钮图片
		}
	}

	/**
	 * 初始化内置快速播放内容
	 */
	public static void iniFastPlayData(SQLiteDatabase db) {
		List<PlayRecord> playRecordList = new ArrayList<PlayRecord>();
		PlayRecord record1 = new PlayRecord();
		record1.setPlayRecordCID(4080041l);
		record1.setPlayRecordCCID(1734047l);
		record1.setPlayRecordCLID(0l);
		record1.setPlayRecordVideoID(111207718l);
		record1.setPlayRecordType(PlayRecord.RECORD_PLAYER_NETWORK);
		record1.setPlayRecordContentType(9);
		record1.setPlayRecordName("100tv展示1");
		record1.setPlayRecordImageUrl("http://d.17url.net:82/mv/upload/columns/201407/10/201407101740129765.jpg?1404985212417");
		record1.setPlayRecordPlayUrl("[host]/player/xyzplay?cid=4080041&ccid=1734047&ifp=29&clid=0&videoid=111207718&loop=1&actionpath=38%7C23&dfnt=3");
		record1.setPlayRecordAlreadyPlayTime(0l);
		record1.setPlayRecordTotalTime(70040l);
		record1.setPlayRecordCreateTime(System.currentTimeMillis());
		record1.setPlayRecordIsVIP(false);
		record1.setPlayRecordDescription("100TV高清播放器针对高端平台触摸屏操作特点，精心设计了软件界面，带给用户顶级体验。");
		record1.setPlayRecordFavouriteUrl("[host]/player/collection?clid=0&videoid=111207718&ccid=1734047&cid=4080041");
		record1.setPlayRecordDetailUrl("[host]/player/vgdetail?cid=4080041&ccid=1734047&ifp=29&clid=0&videoid=111207718&loop=1&actionpath=38%7C23&dfnt=3");
		record1.setPlayRecordShareUrl("http://m.100tv.com/clients/100tvPlayer_Android.apk");
		record1.setPlayRecordSynchronzieType(PlayRecord.PLAY_RECORD_SYNCHRONZIE_ADD_WAIT);
		playRecordList.add(record1);

		PlayRecord record2 = new PlayRecord();
		record2.setPlayRecordCID(4080044l);//
		record2.setPlayRecordCCID(1734043l);//
		record2.setPlayRecordCLID(0l);
		record2.setPlayRecordVideoID(111207719l);//
		record2.setPlayRecordType(PlayRecord.RECORD_PLAYER_NETWORK);
		record2.setPlayRecordContentType(9);
		record2.setPlayRecordName("100tv展示2");//
		record2.setPlayRecordImageUrl("http://d.17url.net:82/mv/upload/columns/201407/10/201407101740129765.jpg?1404985212417");//
		record2.setPlayRecordPlayUrl("[host]/player/xyzplay?cid=4080044&ccid=1734043&ifp=29&clid=0&videoid=111207719&loop=1&actionpath=38%7C23&dfnt=3");//
		record2.setPlayRecordAlreadyPlayTime(0l);
		record2.setPlayRecordTotalTime(31160l);//
		record2.setPlayRecordCreateTime(System.currentTimeMillis());
		record2.setPlayRecordIsVIP(false);
		record2.setPlayRecordDescription("100TV高清播放器针对高端平台触摸屏操作特点，精心设计了软件界面，带给用户顶级体验。");//
		record2.setPlayRecordFavouriteUrl("[host]/player/collection?clid=0&videoid=111207719&ccid=1734043&cid=4080044");//
		record2.setPlayRecordDetailUrl("[host]/player/vgdetail?cid=4080044&ccid=1734043&ifp=29&clid=0&videoid=111207719&loop=1&actionpath=38%7C23&dfnt=3");//
		record2.setPlayRecordShareUrl("http://m.100tv.com/clients/100tvPlayer_Android_2.1.8.apk");
		record2.setPlayRecordSynchronzieType(PlayRecord.PLAY_RECORD_SYNCHRONZIE_ADD_WAIT);
		playRecordList.add(record2);

		for (PlayRecord playRecord : playRecordList) {
			ContentValues values = new ContentValues();
			values.put(IFoneDatabase.PLAY_RECORD_CID, playRecord.getPlayRecordCID());
			values.put(IFoneDatabase.PLAY_RECORD_CCID, playRecord.getPlayRecordCCID());
			values.put(IFoneDatabase.PLAY_RECORD_CLID, playRecord.getPlayRecordCLID());
			values.put(IFoneDatabase.PLAY_RECORD_VIDEO_ID, playRecord.getPlayRecordVideoID());
			values.put(IFoneDatabase.PLAY_RECORD_TYPE, playRecord.getPlayRecordType());
			values.put(IFoneDatabase.PLAY_RECORD_CONTENT_TYPE, playRecord.getPlayRecordContentType());
			values.put(IFoneDatabase.PLAY_RECORD_NAME, playRecord.getPlayRecordName());
			values.put(IFoneDatabase.PLAY_RECORD_IMAGE_URL, playRecord.getPlayRecordImageUrl());
			values.put(IFoneDatabase.PLAY_RECORD_PLAY_URL, playRecord.getPlayRecordPlayUrl());
			values.put(IFoneDatabase.PLAY_RECORD_ALREADY_PLAY_TIME, playRecord.getPlayRecordAlreadyPlayTime());
			values.put(IFoneDatabase.PLAY_RECORD_TOTAL_TIME, playRecord.getPlayRecordTotalTime());
			values.put(IFoneDatabase.PLAY_RECORD_CTEATE_TIME, playRecord.getPlayRecordCreateTime());
			values.put(IFoneDatabase.PLAY_RECORD_IS_VIP, playRecord.getPlayRecordIsVIP());
			values.put(IFoneDatabase.PLAY_RECORD_DESCRIPTION, playRecord.getPlayRecordDescription());
			values.put(IFoneDatabase.PLAY_RECORD_FAVOURITE_URL, playRecord.getPlayRecordFavouriteUrl());
			values.put(IFoneDatabase.PLAY_RECORD_DETAIL_URL, playRecord.getPlayRecordDetailUrl());
			values.put(IFoneDatabase.PLAY_RECORD_SHARE_URL, playRecord.getPlayRecordShareUrl());
			values.put(IFoneDatabase.PLAY_RECORD_SYNCHRONZIE_TYPE, playRecord.getPlayRecordSynchronzieType());
			db.insert(IFoneDatabase.TB_PLAY_RECORD, null, values);
		}
	}

	/**
	 * 从资产目录拷贝默认分享图片至应用文件夹下
	 */
	public static synchronized void copyDefaultShareimage() {

		new Thread() {
			public void run() {
				InputStream is = null;
				FileOutputStream fos = null;
				try {
					File file = new File(ApplicationManage.getGlobalContext().getFilesDir(), "defaultImage.jpg");
					if (file.exists() && file.length() > 0) {
						return;
					}
					file.createNewFile();
					is = ApplicationManage.getGlobalContext().getAssets().open("default_weixin160.jpg");
					fos = new FileOutputStream(file);
					int len = 0;
					byte[] buffer = new byte[1024];
					while ((len = is.read(buffer)) != -1) {
						fos.write(buffer, 0, len);
					}

				} catch (IOException e) {
					e.printStackTrace();
				} finally {
					try {
						if (is != null) {
							is.close();
						}
						if (fos != null) {
							fos.close();
						}
					} catch (Exception e) {
					}
				}
			};
		}.start();
	}

	/**
	 * 默认分享图片
	 * 
	 * @return
	 */
	public static boolean isDefaultShareimageExists() {
		File file = new File(ApplicationManage.getGlobalContext().getFilesDir() + "/defaultImage.jpg");
		return file.exists() && file.length() > 0;
	}

	/**
	 * 添加通知log
	 * 
	 * @param log
	 */
	public static synchronized void writeNotificationLog(String log) {
		L.v(TAG, "writeNotificationLog", " writeNotificationLog is start !  log : " + log);

		// TODO 上线前关闭
		if (TextUtils.isEmpty(log) || L.mode_for_release) {
			return;
		}

		String pathDir = Environment.getExternalStorageDirectory().getPath() + "/100tv/notificaticon_log";

		File dir = new File(pathDir);
		if (!dir.exists()) {
			dir.mkdirs();
		}
		File file = new File(dir, android.os.Build.MODEL + ".log");

		if (!file.exists()) {
			try {
				file.createNewFile();
			} catch (IOException e) {
				L.e(TAG, "writeNotificationLog", e.getMessage());
			}
		}

		FileWriter fw = null;
		BufferedWriter bw = null;
		try {
			fw = new FileWriter(file, true);
			bw = new BufferedWriter(fw);
			bw.newLine();
			bw.write(log + "\r\n");
			bw.flush();
		} catch (Exception e) {
			L.e(TAG, "writeNotificationLog", e.getMessage());
		} finally {
			try {
				if (bw != null) {
					bw.close();
				}
			} catch (Exception e) {
				L.e(TAG, "writeNotificationLog", e.getMessage());
			}
		}
	}

	/**
	 * 根据乐视url获取乐视视频vid
	 * 
	 * @param ourl
	 * @return
	 * @return long
	 * @throws
	 */
	public static long getLetvVidByUrl(String ourl) {
		if (ourl.contains("vplay_")) {
			// m.letv.com解析方式
			long videoId = 0;
			try {
				String vid = ourl.substring(ourl.indexOf("vplay_") + 6, ourl.indexOf(".html"));
				videoId = Long.parseLong(vid);
			} catch (Exception e) {
				videoId = 0;
			}
			return videoId;
		} else if (ourl.contains("vplay/")) {
			// www.letv.com解析方式
			long videoId = 0;
			try {
				String vid = ourl.substring(ourl.indexOf("vplay/") + 6, ourl.indexOf(".html"));
				videoId = Long.parseLong(vid);
			} catch (Exception e) {
				videoId = 0;
			}
			return videoId;
		} else {
			return 0;
		}
	}

	/**
	 * 保存第三方播放记录，包括SDK播放，H5播放
	 * 
	 * @param xyzplay 播放地址
	 * @param ourl 原网页地址
	 * @param btnply 显示高清播放按钮
	 * @param weibourl 分享地址
	 * @param pic 图片地址
	 * @param name 名称
	 * @return void
	 * @throws
	 */
	public static void save3rdRecord(String xyzplay, String ourl, int btnply, String weibourl, String pic, String name) {
		PlayRecord record = new PlayRecord();
		record.setPlayRecordType(PlayRecord.RECORD_WEB_SOURCE);
		record.setPlayRecordPlayUrl(xyzplay);
		record.setPlayRecordExternalUrl(ourl);
		record.setPlayRecordIsShowPlayButton(btnply == 0 ? false : true);
		record.setPlayRecordShareUrl(weibourl);
		if (!TextUtils.isEmpty(pic)) {
			record.setPlayRecordImageUrl(formatUrl(pic));
		}
		record.setPlayRecordCID(String2Long(getCIdByUrl(xyzplay)));
		record.setPlayRecordCCID(FoneUtil.String2Long(FoneUtil.getCCIdByUrl(xyzplay)));
		record.setPlayRecordCLID(FoneUtil.String2Long(FoneUtil.getCLIdByUrl(xyzplay)));
		record.setPlayRecordVideoID(FoneUtil.String2Long(FoneUtil.getVideoIdByUrl(xyzplay)));
		record.setPlayRecordName(name);
		record.setPlayRecordCreateTime(System.currentTimeMillis());
		PlayRecordFragment.addRecord(record);
	}

	/**
	 * 根据包名判断此应用是否安装,如果安装了就返回应用信息，如果未安装返回空
	 * 
	 * @param packageName
	 * @return
	 */
	public static PackageInfo checkApkExist(Context context, String packageName) {
		if (TextUtils.isEmpty(packageName))
			return null;
		try {
			return context.getPackageManager().getPackageInfo(packageName, PackageManager.GET_UNINSTALLED_PACKAGES);
		} catch (NameNotFoundException e) {
			return null;
		}
	}

	/**
	 * 根据包名启动第三方应用
	 * 
	 * @param context
	 * @param packageName
	 * @return void
	 * @throws
	 */
	public static void start3rdApp(Context context, String packageName) {
		if (checkApkExist(context, packageName) != null) {
			// 启动
			Intent intent = context.getPackageManager().getLaunchIntentForPackage(packageName);
			context.startActivity(intent);
		}
	}

}
